<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Good;
use App\Models\Position;
use App\Http\Controllers\Taobao\top\TopClient;
use App\Http\Controllers\Taobao\top\request\TbkItemInfoGetRequest;
use App\Http\Controllers\Taobao\top\request\TbkItemConvertRequest;
use Illuminate\Support\Facades\DB;

class GoodController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $positions = Position::get();

        return view('admin.good.index',compact('positions'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {
        $model = new Good();
        $res = $request->only(['nid','name','min_amount','max_amount','start_price','end_price','start_time','end_time','status','min_active','max_active','from','type']);
        if (!empty($res)){
            if ($res['nid']){
                $model = $model->where('num_iid','like','%'.$res['nid'].'%');
            }
            if ($res['name']){
                $model = $model->where('goods_name','like','%'.$res['name'].'%');
            }
            if ($res['start_price'] && !$res['end_price']){
                $model = $model->where('actual_price','>=',$res['start_price']);
            }elseif (!$res['start_price'] && $res['end_price']){
                $model = $model->where('actual_price','<=',$res['end_price']);
            }elseif ($res['start_price'] && $res['end_price']){
                $model = $model->whereBetween('actual_price',[$res['start_price'],$res['end_price']]);
            }
            if ($res['min_amount'] && !$res['max_amount']){
                $model = $model->where('coupon_amount','>=',$res['min_amount']);
            }elseif (!$res['min_amount'] && $res['max_amount']){
                $model = $model->where('coupon_amount','<=',$res['max_amount']);
            }elseif ($res['min_amount'] && $res['max_amount']){
                $model = $model->whereBetween('coupon_amount',[$res['min_amount'],$res['max_amount']]);
            }
            if ($res['start_time'] && !$res['end_time']){
                $model = $model->where('active_time','>=',$res['start_time']);
            }elseif (!$res['start_time'] && $res['end_time']){
                $model = $model->where('active_time','<=',$res['end_time']);
            }elseif ($res['start_time'] && $res['end_time']){
                $model = $model->whereBetween('active_time',[$res['start_time'],$res['end_time']]);
            }
            if ($res['status']!=3 && isset($res['status'])){
                $model = $model->where('shelf_status',$res['status']);
            }
            if ($res['min_active'] && !$res['max_active']){
                $model = $model->where('shelf_time','>=',$res['min_active']);
            }elseif (!$res['min_active'] && $res['max_active']){
                $model = $model->where('shelf_time','<=',$res['max_active']);
            }elseif ($res['min_active'] && $res['max_active']){
                $model = $model->whereBetween('shelf_time',[$res['min_active'],$res['max_active']]);
            }
            if ($res['type'] && isset($res['type'])){
                $model = $model->where('from_type',$res['type']);
            }
        }
        $res = $model->orderBy('weigh','desc')->orderBy('sort','desc')->orderBy('id','desc')->paginate($request->get('limit',30))->toArray();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

    //添加商品页面
    public function create()
    {
        return view('admin.good.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        include __DIR__ . "/../Taobao/TopSdk.php";
        $this->validate($request,[
            'content' => 'required|min:4|max:400'
        ]);
        if (empty($request->get('content'))){
            return back()->withInput()->with(['status'=>'请填写索要获取商品信息']);
        }
        $data = $request->only(['content']);
        $list = explode(",",$data["content"]);
        $insertData = [];
        $model = new Good();
        foreach ($list as $key=>$item){
            $goodsInfo = DB::table("goods")->where("num_iid",$item)->orderBy('id','desc')->first();
            $goodsInfo = json_decode(json_encode($goodsInfo), true);
            $url = "http://tkapi.apptimes.cn/coupon?appkey=".getenv('TKAPI_APP_KEY')."&pid=".getenv('TKAPI_PID')."&good_id=".$item;
            $res=curl_request($url);//file_get_contents
            $res = json_decode($res,true);
            if (empty($res['errcode'])){
                $resData = $res['data'];
                $info['from_type'] = 1;
                $info['num_iid']  = $resData["item_id"];
                $info['cate_id'] = $resData["category_id"];
                $info['coupon_url'] = $resData["coupon_click_url"];
                $info['com_rate'] = $resData["max_commission_rate"];
                $info['item_url'] = $resData["item_url"];
                if (isset($resData['coupon_type'])){
                    $info['coupon_info'] = $resData["coupon_info"];
                    $info['coupon_remain_count'] = $resData["coupon_remain_count"];
                    $info['coupon_type'] = $resData["coupon_type"];
                }
                $e = str_replace("https://uland.taobao.com/coupon/edetail?e=","",$resData["coupon_click_url"]);
                $url = "http://tkapi.apptimes.cn/coupon/info?appkey=uiwbqiwl&e=".$e;
                $comInfo = file_get_contents($url);
                $comInfo = json_decode($comInfo,true);
                if (empty($comInfo['errcode'])){
                    $comData = $comInfo['data'];
                    $comItem = $comData['item'];
                    $headUrl = "https:";
                    $info['shop_name'] = $comData['shopName'];
                    $info['shop_logo'] = $headUrl.$comData['shopLogo'];
                    $info['tao_pid'] = $comData['pid'];
                    $info['retStatus'] = $comData['retStatus'];
                    $info['sell_price'] = $comItem['reservePrice'];
                    $info['actual_price'] = $comItem['discountPrice'];
                    $info['pic_url'] = $headUrl.$comItem['picUrl'];
                    $info['share_url'] = $headUrl.$comItem['shareUrl'];
                    $info['com_url'] = $headUrl.$comItem['clickUrl'];
                    $info['goods_name'] = $comItem['title'];
                    $info['tao_sale'] = $comItem['biz30Day'];
                    $now = date("Y-m-d H:i:s");
                    if ($comData['retStatus']==0){
                        //劵正常
                        $info['shelf_status'] = 1;
                        $info['shelf_time'] = date("Y-m-d");
                        $info['coupon_amount'] = $comData['amount'];
                        $info['active_start_time'] = $comData['effectiveStartTime'];
                        $info['active_end_time'] = $comData['effectiveEndTime'];
                    }else{
                        //劵失效了
                        $info['shelf_status'] = 0;
                        $info['coupon_amount'] = 0;
                        $info['active_start_time'] = null;
                        $info['active_end_time'] = null;
                    }
                    if (empty($goodsInfo)){
                        $info['updated_at'] = $now;
                        $info['created_at'] = $now;
                        $insertData[] = $info;
                    }else{
                        $model->where("num_iid",$item)->update($info);
                    }
                }
            }else{
                $msg=$res['errmsg'];
                return back()->withErrors($msg);
            }

        }
        if (!empty($insertData)) $model->insert($insertData);
        return back()->with(['status'=>'商品添加成功']);
      /*  $c = new TopClient;
        $req = new TbkItemInfoGetRequest;
        $req->setNumIids($data['content']);
        $resp = $c->execute($req);
        $result = json_decode(json_encode($resp),true);
        if (isset($result['code'])) return back()->withInput()->with(['status'=>'远程获取商品数据失败'.$result['sub_code']]);
        $insertData = [];
        $lists = [];
        $list = $result['results']['n_tbk_item'];
        if (empty($lis[0])) $lists['0'] = $list;
        foreach ($lists as $key=>$item){

        }*/
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)){
            return response()->json(['code'=>1,'msg'=>'请选择删除项']);
        }
        if (Good::destroy($ids)){
            return response()->json(['code'=>0,'msg'=>'删除成功']);
        }
        return response()->json(['code'=>1,'msg'=>'删除失败']);
    }
}
